package com.cofluent.web.server;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;

import org.w3c.dom.DOMException;

import com.cofluent.web.client.BuildInformationService;
import com.cofluent.web.client.model.Build;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class BuildInformationServiceImpl extends RemoteServiceServlet implements BuildInformationService
{
	private static final long serialVersionUID=2675654150042921062L;
	private static final String INPUT_FILE_NAME = "builds.xml";
	public static URL INPUT_FILE_URL=BuildInformationServiceImpl.class.getResource("/"+INPUT_FILE_NAME);

	private boolean refreshed=false;

	private ArrayList<Build> builds;
	
	public void refresh()
	{
//		URL url=getClass().getResource("/"+INPUT_FILE_NAME);
		builds = new ArrayList<Build>();
		try {
			if(INPUT_FILE_URL==null)
				System.err.println("Unable to find " + INPUT_FILE_NAME);
			else
			{
				InputStream stream = INPUT_FILE_URL.openStream();
				BuildElements buildElements=(BuildElements) XMLSerializerUtil.unmarshal(BuildElements.class, stream);
				for (Iterator iter = buildElements.getBuildElements().iterator(); iter.hasNext();) {
					BuildElement buildElement = (BuildElement) iter.next();
					builds.add(buildElement.getBuild());
				}
				stream.close();
				refreshed=true;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Build[] getBuilds()
	{
		if(!refreshed)
			refresh() ;
		return (Build[]) builds.toArray(new Build[builds.size()]) ;
	}

//	public Build getPendingBuildInformation() {
//		// TODO Auto-generated method stub
//		return null;
//	}
//
//	public void tagPendingBuild() {
//		// TODO Auto-generated method stub
//		
//	}
	public void delete(Build build)
	{
		try
		{
			InputStream inputStream=BuildInformationServiceImpl.INPUT_FILE_URL.openStream();
			BuildElements buildElements=(BuildElements)XMLSerializerUtil.unmarshal(BuildElements.class, inputStream);
			inputStream.close();
			for (Iterator iterator=buildElements.getBuildElements().iterator(); iterator.hasNext();)
			{
				BuildElement buildElement=(BuildElement)iterator.next();
				if(buildElement.getBuild().equals(build))
				{
					buildElements.remove(buildElement);
					iterator=buildElements.getBuildElements().iterator();
				}
			}
			// write file:
			File file=new File(BuildInformationServiceImpl.INPUT_FILE_URL.toURI());
			XMLSerializerUtil.marshall(buildElements, file);
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (URISyntaxException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (DOMException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
